<template>
    <div class="Address">
      <div class="header">
        <van-nav-bar title="地址管理" fixed  right-text left-arrow @click-left="onClickLeft"/>
      </div>
      <div class="Address_con">
        <div class="Address_content" >
          <van-list
            v-model="loading"
            :finished="finished"
            :finished-text="text"
            @load="onLoad"
            :offset="100"
            :immediate-check="false"
          >
            <ul v-if="filterAddress.list && filterAddress.list.length>0">
            <li v-for="(item,index) in filterAddress.list" >
              <div @click="toCart(item)">
                <h6 class="title">
                  {{item.name}}&nbsp;&nbsp;&nbsp;&nbsp;{{item.phone}}
                </h6>
                <p class="address" >
                  {{item.province}}&nbsp;{{item.city}}&nbsp;{{item.county}}&nbsp; {{item.detailed}}
                </p>
              </div>

              <div class="editWrap">
                <span class="el-icon-delete" @click="remove(item,index)"> <i class="icon iconfont icon-shanchu"></i>删除</span>
                <span class="el-icon-delete" @click="goUserAddress(item)" style="padding-left: 0.4rem">修改</span>
                <div class="el-icon-edit-outline" v-if="item.is_default==!setDefault">
                  <div class="set_default" @click="setDefaultAddress(index,item)">
                  </div>
                  <span>默认地址</span>
                </div>
                <div class="el-icon-edit-outline" v-if="item.is_default==setDefault">
                  <div class="default" @click="setDefaultAddress(index,item)">
                  </div>
                  <span>设为默认</span>
                </div>
              </div>
            </li>
            </ul>
              <div class="empty" v-else>暂无数据</div>
          </van-list>
        </div>
        <div class="Address_foot">
          <router-link to="/nesAddress">
          <button>新增地址</button>
          </router-link>
        </div>
      </div>
    </div>
</template>

<script>
    export default {
        name: "Address",
      data(){
          return{
            filterAddress:[],
            filterAddressList:[],
            page: 1,//页码
            showlaoding: true, //是否显示loading效果
            setDefault:false,//记录是否设为默认地址
            choosedAddressId: null,//当前被选中的地址的ID
            checkbox:false,
            //下拉刷新
            isLoading: false,
            //上拉加载
            loading: false,
            finished: false,
						text:'',
          }
      },
      mounted: function () {
        this.getUserAddress(this.page)
      },
      methods:{
        //返回
        onClickLeft() {
          this.$router.go(-1);
        },
        onLoad(){
          // 上拉加载
          if (this.filterAddress.list && this.filterAddress.list.length > 0) {
              this.getUserAddress();// 上拉触发的分页查询
            }
        },
        //调用用户地址
        async getUserAddress(){
          var userList=[]
          var userList=JSON.parse(localStorage.getItem('userInfo'))
          this.userList=userList
          this.showlaoding = true //'userList.user_id
          let params = {
            user_id:userList.userId,
            pageNum:this.page,
            pageSize:10
          };
          const res = await this.$axios.post(this.$api.userAddresslist, params);
          if (res.success) {
            if (this.loading) {
              this.filterAddressList = this.commodityList.concat(res.data.list);
              this.filterAddress = res.data;
              this.filterAddress.list = this.filterAddressList;
              var filterAddressData=res.data.list;
              for(var i in filterAddressData){
                    if(filterAddressData[i].is_default){
                        this.setDefault = true
                    }
                  }
              if (this.filterAddress.list.length >= this.filterAddress.total) {
                this.finished = true;
              } else {
                this.page++;
              }
            } else {
              this.filterAddress = res.data;
              if (this.filterAddress.list.length >= this.filterAddress.total) {
                this.finished = true;
                this.text='没有更多了'
              }
            }
            this.isLoading = false;
            this.loading = false;
          }
            // if (res.success) {
            //   let filterAddress = res.data.list
            //   for(var i in filterAddress){
            //     if(filterAddress[i].is_default){
            //       this.setDefault = true
            //     }
            //   }
            //   filterAddress.map(n => this.filterAddress.push(n))
            //   this.filterAddress.forEach(n => {
            //     const d = new Date(n.create_at)
            //     n.create_at = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
            //   })
            //     this.showlaoding = false
            //   }
        },
        goUserAddress(item){
          this.$router.push({name: '编辑地址', query: {
              name:item.name, phone:item.phone, province:item.province, city:item.city,
              county:item.county,detailed:item.detailed,id:item.id
            }})
        },

        //点击修改默认地址
        setDefaultAddress:function(index,item){
          var list=[]
          var list=JSON.parse(localStorage.getItem('userInfo'))
          this.list=list
          var userID = list.userId;
          const formDatas=new FormData()
          this.$axios.post('/api/common/v1/CoverageUserAddress/queryUserAddress?user_id='+userID+'&pageNum='+this.page,{
            params: {}
          }).then(res => {
            console.log('错误123', this.filterAddress.list[index].is_default);
            if (this.filterAddress.list[index].is_default == false) {
              formDatas.append('user_id',userID)
              formDatas.append('name',item.name)
              formDatas.append('phone',item.phone)
              formDatas.append('province',item.province)
              formDatas.append('city',item.city)
              formDatas.append('county',item.county)

              formDatas.append('detailed',item.detailed)
              formDatas.append('is_default','1')
              formDatas.append('id',item.id)
              this.$axios({
                method:"post",
                url: '/api/common/v1/CoverageUserAddress/UpdateUserGoodsAddress',
                data:formDatas,
                headers: {
                  'Content-Type':'multipart/form-data'
                }
              }).then(res=>{
                this.$toast("修改成功");
                 this.getUserAddress()
              })
            }
            else {//数据库存在收藏,点击删除收藏操作
              formDatas.append('user_id',userID)
              formDatas.append('name',item.name)
              formDatas.append('phone',item.phone)
              formDatas.append('province',item.province)
              formDatas.append('city',item.city)
              formDatas.append('county',item.county)
              formDatas.append('detailed',item.detailed)
              formDatas.append('is_default','0')
              formDatas.append('id',item.id)
              this.$axios({
                method:"post",
                url: '/api/common/v1/CoverageUserAddress/UpdateUserGoodsAddress',
                data:formDatas,
                headers: {
                  'Content-Type':'multipart/form-data'
                }
              }).then(res=>{

                this.getUserAddress()
              })
              console.log('8888');
            }
          }, function (error) {
            console.log('错误', error);
          })
        },
        //  删除地址
        async remove(item,index){
          var list=[]
          var list=JSON.parse(localStorage.getItem('userInfo'))
          this.list=list
          var userID = list.userId;
          let Id= item.id;
          let params = {
            user_id:userID,
            id:Id,
          };
          const res = await this.$axios.post(this.$api.DeleteUserGoodsAddress, params);
            if (res.success) {
              this.filterAddress.list.splice(index, 1); //删除数组下表为index的1个数组
              this.$toast("删除成功");
            }
        },
        toCart(item){
          // this.$router.push({path: '/cart', query:{id:item.id}})
          this.$router.go(-1);//返回上一层
          localStorage.setItem('Address',JSON.stringify(item));
        },
      },
      created:function () {
        //隐藏公用底部
        this.$emit('public_footer', false);
        setTitle('地址管理')
      }
    }
</script>

<style scoped>
  @import '../../assets/css/index.css';
  .Address_content ul{
    padding-bottom: 0.1rem;
  }
  .default {
    width: 0.2rem;
    height: 0.2rem;
    position: relative;display: inline-block;
    border: 1px solid grey;
    border-radius: 2rem;
    top: 0.05rem;
    left: 0;
  }

  .set_default {
    display: inline-block;
    border: 1px solid ghostwhite;
    border-radius: 1.8rem;
    cursor: pointer;
    position: relative;
    width: 0.2rem;
    height: 0.2rem;
    top: 0.05rem;
    left: 0;
    border-radius: 2rem;
    -moz-border-radius: 2rem;      /* Gecko browsers */
    -webkit-border-radius:2rem;   /* Webkit browsers */
    background-color: #01bf47;
    /* W3C syntax */
  }
  .set_default:after {
    /*opacity: 0;*/
    content: '';
    position: absolute;
    width: 0.06rem;
    height: 0.05rem;
    background: transparent;
    top: 0.05rem;
    left: 0.05rem;
    border: 2px solid #fff;
    border-top: none;
    border-right: none;
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
  }
  /*.mycheck input[type=checkbox]:checked + label {*/
    /*background: #01bf47;*/
    /*border: 0;*/
  /*}*/
  /*.mycheck input[type=checkbox]:checked + label:after {*/
    /*opacity: 1;*/
  /*}*/
</style>
